package com.araaya.eslimsmobile.util;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;

import com.araaya.eslimsmobile.R;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


public class FileBrowser extends ListActivity {

	private FileBrowserAdapter fileList;
	private String path;
	private ArrayList<File> fileLst;
	private File file; 
	private FilenameFilter filter;

	
	
	/** Called when the activity is first created. */

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// TODO: if SD card is mounted start from there
		filter = new FilenameFilter() {
			@Override
			public boolean accept(File dir, String filename) {
				File sel = new File(dir, filename);
				return (sel.isFile() || sel.isDirectory()) && !sel.isHidden() && isKML(sel) ;
			}
			
			/**
			 * Returns true if it's a file and a KML
			 * @param sel CWD File
			 * @return boolean true if it's KML file or a directory
			 */
			private boolean isKML(File sel) {
				if(sel.isFile()){
					return sel.getName().endsWith(".kml")? true : false;
				}else{
					return true;
				}
			}
		};
		
		// If SD card mounted start from there
		if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
		    file = Environment.getExternalStorageDirectory();
		    path = file.getPath()+"/";
		}
		
		this.getDir();
	}
	
	/**
	 * List the file list in current file path
	 */
	private void getDir(){
		fileLst =new ArrayList<File>();
		if(file==null){ 						// if the file isn't initialized
			file= new File("/");
			path=file.getPath();
		}
		if(file.getParentFile()!=null){ 		// if the file doesn't have a parent file
			fileLst.add(new File("../"));
			Log.d("DEBUG","Parent File :"+file.getParentFile());
		}
		
		File[] files = file.listFiles(filter);
		Log.d("DEBUG", "Files=======>> "+files.length);
		for(File fl: files){
			fileLst.add(fl);
		}
		fileList =new FileBrowserAdapter(this, fileLst);
		setListAdapter(fileList);
	}

	@Override
	protected void onListItemClick(ListView l, View v, final int position,long id) {
		String fileName= ((TextView)v.findViewById(R.id.fpath)).getText().toString();
		/**
		 * We update the currently working file in each click 
		 */
		if(fileName.equals("../")){
			shiftToParentDir();
		}else{
			path+=fileName;
			file = new File(path);
		}
		
		Log.d("DEBUG", "Clicked file: "+file.getAbsolutePath()+" is Directory: "+file.isDirectory());
		
		if (file.isDirectory()){
			/**
			 * Here we manages the all navigation if the clicked file is a directory current working.
			 */
			if (file.canRead()){
				getDir();
			}else{
				new AlertDialog.Builder(this)
				.setIcon(R.drawable.information)
				.setTitle("[" + file.getName() + "] folder cannot read")
				.setPositiveButton("OK",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						shiftToParentDir();
					}
				}).show();
			}
		}else{
			LinearLayout layout = new LinearLayout(getApplicationContext());
			new AlertDialog.Builder(this)
			.setView(layout)
			.setTitle("Import KML")
			.setMessage("Import "+ fileName +" to eSlims?")
			.setPositiveButton("OK",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							finish();
						}
					})
			.setNegativeButton("Cancel",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
							shiftToParentDir();
							return;

						}
					})
			.show();
		}
	}
	
	/**
	 * Returns back to parent directory of CWD
	 */
	private void shiftToParentDir() {
		if(file.getParentFile()!=null){
			file=file.getParentFile();
			String temp=file.getAbsolutePath();
			path=(temp.equals("/")? temp : temp+"/");
		}
	}
	
	@Override
	public void finish(){
		Intent data = new Intent();
		data.putExtra("KML_File", file);
		setResult(RESULT_OK, data);
		super.finish();
	}
	
	@Override
	public void onBackPressed() {
		if(file.isFile()){
			shiftToParentDir();
			getDir();
		}else{
			super.onBackPressed();
		}
	}
}

